
import lotteryService from '../../services/lottery';
import config from '../../config/api';
const app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    conditionType:0,
    dates:[],
    hours:[
      '00','01','02','03','04','05','06','07','08','09',10,11,12,13,14,15,16,17,18,19,20,21,22,23
    ],
    minutes:["00","30"],
    isShowPicker:false,
    currentAwardType:0,
    imgPath:"../img/bg.png",
    vip: app.globalData.vip, // 是否是vip用户,
    date: "",
    hour:'00',
    minute:'00',
    isVipHidden:true
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    debugger; 
    let now = new Date();
    let dates = [];
    if (now.getMinutes() < 30){
      this.setData({
        hour: now.getHours() < 10 ? '0' + now.getHours() : now.getHours(),
        minute:'30' 
      });
    }else{
      this.setData({
        hour: (now.getHours() + 1) < 10 ? '0' + (now.getHours() + 1) : now.getHours() + 1,
        minute:'00'
      });
    }
    this.setData({
      hour: now.getHours() < 10 ? '0' + now.getHours() : now.getHours(),
      minute: now.getMinutes() < 30?30:'00'
    })
    for(let i =0;i<7;i++){
      let targetMS = now.getTime()+1000*60*60*24*i;
      let targetDate = new Date(targetMS);
      let year = targetDate.getFullYear();
      let month = targetDate.getMonth()+1;
      if (month<10){
        month = "0" + month; 
      }
      let date = targetDate.getDate();
      if (date<10){
        date = "0" + date;
      }
      let str= [year,month,date].join("-");
      if(i==0){
        this.setData({
          date: str
        });
      }
      dates.push(str);
    }
    this.setData({
      dates: dates,
      imgPath: "../img/bg.png",
      awardNameValue:'',
      awardNumberValue:'',
      moneyValue:'',
      moneyCount:'',
      isShowPicker: false,
      awardNameIsValid:true,
      awardNumberIsValid:true,
      moneyIsValid:true,
      moneyCountIsValid:true
    });
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  },
  /**
  * 编辑开奖条件
  */
  editCondition: function(){
    //0：按时间自动开奖 1：按人数自动开奖 2：手动开奖
    const that = this;
    wx.showActionSheet({
      itemList: ['按时间自动开奖', '按人数自动开奖', '手动开奖',"当面开奖"],
      success: function(res) {
        that.setData({
          conditionType:res.tapIndex,
        })
      },
      fail: function(res) {
        console.log(res.errMsg)
      }
    })
  },
  popVip:function(){
    this.setData({
      isVipHidden:false
    });
  },
  closeVip: function () {
    this.setData({
      isVipHidden: true
    });
  },
  /**
   * 购买 vip
   */
  buyVip:function() {
    lotteryService.buyVip().then(res => {
      console.log(res)
      if(res) {
        wx.requestPayment(
          {
            'timeStamp': res.data.timeStamp,
            'nonceStr': res.data.nonceStr,
            'package': res.data.package,
            'signType': 'MD5',
            'paySign': res.data.paySign,
            'success': function (success) { 
              app.globalData.vip = true;
              this.setData({
                isVipHidden: false,
                vip:true
              });
              wx.setStorageSync('vip', true)
            },
            'fail': function (fail) {
              console.log(fail)
             },
            'complete': function (complete) {
              console.log(complete)
             }
          })
      }
    })
      .catch(err => {
        // 发起失败
        console.error(err);
      });
  },
  /**
   * 展示时间选择器
   */
  triggerPickerShow:function() {
    debugger
    this.setData({
      isShowPicker:!this.data.isShowPicker
    });
  },
  /**
   * 时间选择器触发事件
   */
  pickerChange:function(e){
    const val = e.detail.value
    this.setData({
      date: this.data.dates[val[0]],
      hour: this.data.hours[val[1]],
      minute: this.data.minutes[val[2]]
    });
  },
  /**
   * 修改抽奖类型
   */
  switchType:function(e){
    var currentAwardType = e.target.dataset.awardtype || "";
    if (currentAwardType){
      this.setData({
        currentAwardType: currentAwardType
      });
    }
  },
  /**
   * 修改背景图片
   */
  changeImg:function(){
    debugger;
    const that = this;
    wx.chooseImage({
      count: 1, // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        const tempFilePaths = res.tempFilePaths[0];
        const ext = tempFilePaths.substr(tempFilePaths.lastIndexOf(".")+1);
        if(config.Lottery.AllowImgType.indexOf(ext) == -1){
          wx.showModal({
            title: '警告',
            content: '图片格式只支持png,jpg,jpeg',
            success: function(res) {
            }
          })
          return;
        }
        wx.showToast({
          title: '正在上传...',
          icon: 'loading',
          mask: true
        })  
        lotteryService.upload(tempFilePaths)
          .then(res => {
            debugger;
            wx.hideLoading();
            const result = JSON.parse(res.data);
            if (result.resCode == config.Lottery.ResCode.Success) {
              that.setData({
                imgPath: result.data.token
              }); 
            }
          })
          .catch(err => {
            // 发起失败
            wx.hideLoading();
          });
      }
    })
  },
  getPayStatus:function(orderId){
    lotteryService.payStatus(orderId)
      .then(res => {
        wx.hideLoading();
        if (res.resCode == config.Lottery.ResCode.Success) {
          if (res.data.status == 1){
            wx.navigateTo({
              url: '../addSuccess/addSuccess?lotteryId=' + res.data.lottery_id,
            })
          }else{
            this.getPayStatus(orderId);
          }
        }
      })
      .catch(err => {
        // 发起失败
        wx.hideLoading();
      });
  },
  launchValidate:function(data){
    if (this.data.currentAwardType == config.Lottery.Type.Object){
      let awardNumberIsValid = data.awardNumber?true:false;
      let awardNameIsValid =  data.awardName?true:false;
      this.setData({
        awardNumberIsValid,
        awardNameIsValid
      });
      return awardNumberIsValid && awardNameIsValid;
    }else{
      let moneyCountIsValid = data.moneyCount?true:false;
      let moneyIsValid =  data.money?true:false;  
      this.setData({
        moneyCountIsValid,
        moneyIsValid
      });
      return moneyCountIsValid && moneyIsValid;
    }
  },
  /**
   * 发起抽奖
   */
  launchLottery: function(e) {
    if(!this.launchValidate(e.detail.value)){
      return;
    }
    wx.showLoading({
      title: '发起抽奖中...',
      mask: true
    });
    const image = this.data.imgPath == '../img/bg.png' ? '../../pages/img/bg.png' : this.data.imgPath;
    let params = {
      method: this.data.conditionType,
      items:[],
      image: image
    };
    if(config.Lottery.Method.Auto == this.data.conditionType){
      let time = this.data.date + " " + [this.data.hour, this.data.minute,"00"].join(":");
      params.drawnDatetime = time;
    }else if(config.Lottery.Method.JoinedCount == this.data.conditionType){
      params.drawnCount = Number(e.detail.value.lotteryNum);
    }
    params.items = [];
    let item = {
      type: Number(this.data.currentAwardType),
      level:1
    }
    if (this.data.currentAwardType == config.Lottery.Type.Object){
      item.count = Number(e.detail.value.awardNumber);
      item.name =  e.detail.value.awardName;
    }else{
      item.count = Number(e.detail.value.moneyCount);
      item.packet = Number(e.detail.value.money *100);
    }
    params.items.push(item);
    const that = this;
    lotteryService.launch(params)
    .then(res => {
      wx.hideLoading();
      if (res.resCode == config.Lottery.ResCode.Success) {
        if (this.data.currentAwardType == config.Lottery.Type.Packet){
          wx.requestPayment(
            {
              'timeStamp': res.data.timeStamp,
              'nonceStr': res.data.nonceStr,
              'package': res.data.package,
              'signType': res.data.signType,
              'paySign': res.data.paySign,
              'success': function (success) {
                wx.showLoading({
                  title: '发起中...',
                  mask: true
                });
                that.getPayStatus(res.data.orderId)
              },
              'fail': function (fail) {
                wx.showToast({
                  title: '发起失败，请检查抽奖设置',
                  icon: 'none',
                  duration: 2000
                })
              },
              'complete': function (complete) {
                console.log(complete)
              }
            })
        }else{
            wx.navigateTo({
              url: '../addSuccess/addSuccess?lotteryId=' + res.data.lotteryId,
            })
        }
      }else{
        wx.showToast({
          title: '发起失败',
          icon: 'none',
          duration: 2000
        })
      }
    })
    .catch(err => {
      // 发起失败
      wx.showToast({
        title: '发起失败',
        icon: 'none',
        duration: 2000
      })
    });
  },
  validate:function(e){
    debugger;
    const name = e.target.dataset.name ||''
    if(!name){
      return;
    }
    let data={};
    data[name+'IsValid'] = e.detail.value?true:false;
    this.setData(data);
  }
})